package com.htudata.zabbix.problem.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.htudata.core.util.operation.ArrayOperationUtils;
import com.htudata.core.util.operation.StringOperationUtils;
import com.htudata.zabbix.api.service.ProblemZabbixApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ProblemService {

  @Autowired
  private ProblemZabbixApiService problemZabbixApiService;
  
  public static boolean isValidProblemId(String id) {
    if (StringOperationUtils.isPositiveInt(id))
      return true; 
    return false;
  }
  
  public static boolean isTriggerProblem(int source, int object) {
    if (source == 0 && object == 0)
      return true; 
    return false;
  }
  
  public JSONArray getProblems(String[] groupIdArr, int time_from, int time_till, int limit) throws Exception {
    JSONObject params = new JSONObject();
    if (limit > 0)
      params.put("limit", Integer.valueOf(limit)); 
    params.put("sortfield", "eventid");
    params.put("sortorder", "DESC");
    params.put("output", new String[] { "eventid", "name", "clock", "r_clock", "acknowledged", "severity", "source", "object", "objectid" });
    if (ArrayOperationUtils.isValidArr((Object[])groupIdArr))
      params.put("groupids", groupIdArr); 
    if (time_from > 0)
      params.put("time_from", Integer.valueOf(time_from)); 
    if (time_till > 0)
      params.put("time_till", Integer.valueOf(time_till)); 
    params.put("recent", Boolean.valueOf(true));
    String json = this.problemZabbixApiService.getProblems(params);
    JSONObject root = JSON.parseObject(json);
    if (root == null)
      return null; 
    JSONArray result = root.getJSONArray("result");
    return result;
  }
  
  public JSONArray getProblemsByTriggerIds(String[] triggerIdArr, long time_from, long time_till) throws Exception {
    JSONObject params = new JSONObject();
    params.put("sortfield", "eventid");
    params.put("sortorder", "DESC");
    params.put("output", new String[] { "eventid", "name", "clock", "r_clock", "acknowledged", "severity", "source", "object", "objectid" });
    if (ArrayOperationUtils.isValidArr((Object[])triggerIdArr))
      params.put("objectids", triggerIdArr); 
    if (time_from > 0L)
      params.put("time_from", Long.valueOf(time_from)); 
    if (time_till > 0L)
      params.put("time_till", Long.valueOf(time_till)); 
    params.put("recent", Boolean.valueOf(true));
    String json = this.problemZabbixApiService.getProblems(params);
    JSONObject root = JSON.parseObject(json);
    if (root == null)
      return null; 
    JSONArray result = root.getJSONArray("result");
    return result;
  }
}
